<template>
    <div>
        <el-dialog :title="title" :visible.sync="dialogVisible" width="80%">
            <el-form :inline="true" :model="animeForm" :rules="rulesanimeForm" ref="animeForm_">
                <el-form-item label="番名" label-width="100px" prop="name">
                    <el-input v-model="animeForm.name" placeholder="请输入番名"></el-input>
                </el-form-item>
                <el-form-item label="番号" label-width="100px" prop="designation">
                    <el-input v-model="animeForm.designation" placeholder="请输入番号"></el-input>
                </el-form-item>
                <el-form-item label="标签" label-width="100px" prop="labels">
                    <el-select @change="changeLabel" v-model="animeForm.labels" multiple filterable reserve-keyword
                        style="margin-left: 20px;" placeholder="请选择">
                        <el-option v-for="item in labelD" :key="item.id" :label="item.label" :value="item.label">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="总集数" label-width="100px" prop="episodes">
                    <el-input v-model="animeForm.episodes" placeholder="请输入总集数"></el-input>
                </el-form-item>
                <el-form-item label="出品年份" label-width="100px" prop="pubTime">
                    <el-select @change="changeYear" v-model="animeForm.pubTime" filterable style="margin-left: 20px;"
                        placeholder="请选择">
                        <el-option v-for="item in yearD" :key="item.id" :label="item.label" :value="item.label">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="季度" label-width="100px" prop="season">
                    <el-select @change="changeMonth" v-model="animeForm.season" filterable style="margin-left: 20px;"
                        placeholder="请选择">
                        <el-option v-for="item in monthD" :key="item.id" :label="item.label" :value="item.label">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="放送时间" label-width="100px" prop="week">
                    <el-select @change="changeWeek" v-model="animeForm.week" filterable style="margin-left: 20px;"
                        placeholder="请选择">
                        <el-option v-for="item in weekD" :key="item.id" :label="item.label" :value="item.label">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="出品国家" label-width="100px" prop="country">
                    <el-select @change="changeCountry" v-model="animeForm.country" filterable style="margin-left: 20px;"
                        placeholder="请选择">
                        <el-option v-for="item in countryD" :key="item.id" :label="item.label" :value="item.label">
                        </el-option>
                    </el-select>
                </el-form-item>
                <div>
                    <el-form-item label="封面">
                        <el-upload ref="uploadImg" class="avatar-uploader" action="/api/Animes/uploadImg"
                            :show-file-list="true" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload"
                            :auto-upload=false :on-change="preview" :on-preview="handlePictureCardPreview" :limit=1
                            :on-remove="handleRemove" :headers="upheaders">
                            <img v-if="imageUrl" :src="imageUrl" class="avatar">
                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                        <el-button type="success" @click="submitUpload" v-if="true">手动上传</el-button>
                        <el-dialog :visible.sync="dialogVisible2">
                            <img width="100%" :src="dialogImageUrl" alt="">
                        </el-dialog>
                    </el-form-item>
                    <el-form-item label="原图" v-show="isSrcImg">
                        <img :src="srcImg" style="width: 170px;height: 170px;" />
                    </el-form-item>
                    <el-form-item label="简介" style="text-align: center;" label-width="100px" prop="info">
                        <el-input style="width:600px;" type="textarea" show-word-limit maxlength="1500"
                            :autosize="{ minRows: 6, maxRows: 10 }" placeholder="请输入内容" v-model="animeForm.info">
                        </el-input>
                    </el-form-item>
                </div>
                <el-form-item style="position:absolute;bottom:0;right:0;">
                    <el-button type="primary" @click="submitForm($route.name)">确定</el-button>
                    <el-button @click="resetForm">重置</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
        <div>
        </div>
        <div>
            <!-- 表格数据 -->
            <el-table :data="animes" stripe border :highlight-current-row="true" height="560px">
                <el-table-column width="50px" type="index" label="序号"></el-table-column>
                <el-table-column width="150px" prop="name" label="番名" align="center">
                    <template slot="header" slot-scope="scope">
                        番名<el-input v-model="search" @change="searchName($route.name)" size="medium"
                            placeholder="输入关键字搜索" />
                    </template>
                </el-table-column>
                <el-table-column width="180px" prop="cover" label="封面" align="center">
                    <template slot-scope="scope">
                        <img :src="scope.row.cover" style="width: 140px;height: 150px;" />
                    </template>
                </el-table-column>
                <el-table-column width="150px" prop="designation" label="番号" align="center"></el-table-column>
                <el-table-column width="50px" prop="like" sortable label="点赞" align="center"></el-table-column>
                <el-table-column width="100px" prop="week" sortable label="放送时间" align="center"></el-table-column>
                <el-table-column width="100px" prop="pubTime" sortable label="出品年份" align="center"></el-table-column>
                <el-table-column width="100px" prop="season" label="季度" align="center"></el-table-column>

                <el-table-column width="100px" prop="status" label="状态" align="center">
                    <template slot="header" slot-scope="scope">
                        <el-select v-model="status" @change="searchStatus($route.name)">
                            <el-option value="全部">全部</el-option>
                            <el-option value="上架">上架</el-option>
                            <el-option value="下架">下架</el-option>
                        </el-select>
                    </template>
                    <template slot-scope="scope">
                        <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'" disable-transitions>{{
                            scope.row.status === 1 ? '上架' : '下架' }}</el-tag>
                    </template>
                </el-table-column>

                <el-table-column width="300px" label="操作">
                    <template slot="header" slot-scope="scope">
                        <el-button type="success" @click="addNew">新增</el-button>
                        <el-button type="primary" @click="stautsAndName($route.name)">联合查询</el-button>
                    </template>
                    <template slot-scope="scope">
                        <el-button size="mini" type="primary" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                        <el-button size="mini" type="danger"
                            @click="handleDelete(scope.$index, scope.row, $route.name)">删除</el-button>
                        <el-button size="mini" type="warning" @click="handleStatus(scope.$index, scope.row, $route.name)">{{
                            scope.row.status ===
                            1
                            ? '禁用' : '启用' }}</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination background @size-change="handleSizeChange($event, $route.name)"
                @current-change="handleCurrentChange($event, $route.name)" :current-page=pageInfo.currentPage
                :page-sizes="[5, 10, 15, 20]" :page-size=pageInfo.pageSize :page-count="7" :shide-on-single-page=true
                layout="total, sizes, prev, pager, next, jumper" :total=pageInfo.total>
            </el-pagination>
        </div>
    </div>
</template>
<script>

import { getAnimes, addAnime, delAnime, updateAnimeStatus } from '../../api/anime'
import { getDictionary } from '../../api/dictionary'
export default {
    name: 'AnimeItem',
    components: {
    },
    data() {
        return {
            imageUrl: '',//封面
            dialogImageUrl: '',
            dialogVisible2: false,
            upheaders:{
                Authorization:localStorage.getItem("token")
            },//上传图片的 请求头
            srcImg: '',//原图
            title: '',
            isSrcImg: false,
            labelD: [],
            monthD: [],
            countryD: [],
            yearD: [],
            weekD: [],
            animes: [],
            search: '',
            status: '全部',
            dialogVisible: false,
            animeForm: {
                name: '',
                designation: '',
                episodes: 0,
                week: '',
                pubTime: '',
                season: '',
                labels: '',
                country: '',
                like: 50,
                info: '',
                status: 1,
                cover: ''//封面
            },
            pageInfo: {
                total: 0,
                pageSize: 5,
                currentPage: 1
            },
            rulesanimeForm: {
                name: [
                    { required: true, message: '请输入番名', trigger: 'blur' },
                    // { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }
                ],
                designation: [
                    { required: false, message: '请输入番号', trigger: 'blur' },
                    // { min: 11, max: 11, message: '长度为11位', trigger: 'blur' }
                ],
                episodes: [
                    { required: false, message: '请输入总集数', trigger: 'blur' },
                    // { min: 11, max: 11, message: '长度为11位', trigger: 'blur' }
                ],
                week: [
                    { required: true, message: '请输入放送时间', trigger: 'blur' },
                ],
                pubTime: [
                    { required: true, message: '请输入出品年份', trigger: 'blur' },
                ],
                season: [
                    { required: true, message: '请输入季度', trigger: 'blur' },
                ],
                labels: [
                    { required: true, message: '请选择标签', trigger: 'blur' },
                ],
                country: [
                    { required: true, message: '请选择国家', trigger: 'blur' },
                ],
                info: [
                    { required: false, message: '请输入简介', trigger: 'blur' },
                ],
            }
        };
    },
    mounted() {
        var params = {
            "currentPage": this.pageInfo.currentPage,
            "pageSize": this.pageInfo.pageSize,
            "country": this.$route.name
        }
        this.getAnimesData(params)
    },
    watch: {
        $route(to, from) {
            //在这里发送ajax请求
            //获取所有番剧
            this.status = "全部"
            this.search = ''
            var params = {
                "currentPage": this.pageInfo.currentPage,
                "pageSize": this.pageInfo.pageSize,
                "country": to.name
            }
            this.getAnimesData(params)
            console.log(to.name)
        }
    },
    methods: {
        handlePictureCardPreview() {
            this.dialogImageUrl = this.imageUrl;
            this.dialogVisible = true;
        },
        handleRemove(file, fileList) {
            //预览图 移除
            this.imageUrl = ''
        },
        preview(file) {
            this.imageUrl = URL.createObjectURL(file.raw);
        },
        handleAvatarSuccess(res, file) {
            if(res.code==0){
                this.$message({
                    type:'error',
                    message:res.msg
                })
                return;
            }
            //上传成功后，在这里获取 生成的 图片url路径
            // console.log(this.imageUrl);
            //res就是响应返回的图片路径
            console.log(res, "upload:图片路径");
            //回显给  表单cover
            this.animeForm.cover = res
        },
        beforeAvatarUpload(file) {
            const isJPG = file.type === 'image/jpeg' || 'image/png';
            const isLt2M = file.size / 1024 / 1024 < 10;

            if (!isJPG) {
                this.$message.error('上传头像图片只能是 JPG 格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!');
            }
            return isJPG && isLt2M;
        },
        submitUpload() {
            this.$refs.uploadImg.submit()
        },
        submitForm(country) {
            //在这里判断邮箱
            // const qq = /[1-9][0-9]+@qq.com/
            // if (qq.test(this.email)) {
            this.$refs.animeForm_.validate((valid) => {
                if (valid) {
                    // console.log(this.animeForm);
                    //判断，cover是否有值
                    if (this.animeForm.cover == '') {
                        this.$message({
                            type: 'error',
                            message: "等待图片上传中"
                        })
                        return
                    }
                    //将label数组转化为 字符串，用,分割
                    this.animeForm.labels = this.animeForm.labels.join(",")
                    //在这里进行springboot的ajax请求。添加anime
                    addAnime(this.animeForm).then(res => {
                        if (res.data.code === 0) {
                            this.$message({
                                type: 'error',
                                message: res.data.msg
                            })
                            return;
                        }
                        this.$message({
                            type: 'success',
                            message: res.data.msg
                        })
                    }).catch(error => {
                        this.$message({
                            type: 'error',
                            message: '请求接口出错'
                        })
                    })
                    // 提交表单页面并清空
                    this.dialogVisible = false;
                    this.isSrcImg = false
                    this.animeForm = {}
                    //上传图片数据 置空，列表清除
                    this.imageUrl=''
                    this.$refs.uploadImg.clearFiles()
                    //重新加载数据
                    // this.getAnimesData(null)
                    this.stautsAndName(country)
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        showStatus(row, column, cellValue, index) {
            //用来转换状态  1 正常， 0 禁用
            if (cellValue == 1) {
                return '正常'
            } else {
                return '封禁'
            }
        },
        resetForm() {
            console.log('重置');
            this.animeForm = {}
        },
        //用来处理编辑和删除的事件函数
        handleEdit(index, row) {
            //上传列表清空

            this.title = "编辑番剧"
            this.dialogVisible = true
            if (this.animeForm.cover != null || this.animeForm.cover != "") {
                this.isSrcImg = true
            }
            this.srcImg = ''
            //点击编辑回显 表单数据 ，这里用深拷贝
            this.animeForm = JSON.parse(JSON.stringify(row))
            this.srcImg = this.animeForm.cover

            console.log(row)
            //获取字典列表
            this.getD()
        },
        handleDelete(index, row, country) {
            //删除要有提示
            this.$confirm('此操作将永久删除该番剧, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                console.log(row.id);
                //发送ajax请求，
                delAnime(row.id, row.cover).then(res => {
                    console.log("发送了后端请求")
                    if (res.data.code === 0) {
                        this.$message({
                            type: 'error',
                            message: res.data.msg
                        })
                        return;
                    }
                    this.$message({
                        type: 'success',
                        message: res.data.msg
                    })
                }).catch(error => {
                    this.$message({
                        type: 'error',
                        message: "请求接口出错"
                    })
                })
                this.stautsAndName(country)
                // this.getAnimesData()
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        handleStatus(index, row, country) {
            updateAnimeStatus(row.id, row.status === 1 ? 0 : 1).then(res => {
                console.log("发送了后端请求")
                if (res.data.code === 0) {
                    this.$message({
                        type: 'error',
                        message: res.data.msg
                    })
                    return;
                }
                this.$message({
                    type: 'success',
                    message: res.data.msg
                })
            }).catch(error => {
                this.$message({
                    type: 'error',
                    message: "请求接口出错"
                })
            })
            this.animes[index].status = row.status === 1 ? 0 : 1
            this.stautsAndName(country)
            // this.getAnimesData()
            console.log(row.status);
        },
        handleCurrentChange(value, country) {
            this.pageInfo.currentPage = value
            //传递当前页码。
            console.log(value)
            //发送分页请求
            this.stautsAndName(country)
        },
        handleSizeChange(value, country) {
            this.pageInfo.pageSize = value
            //传递当前每页大小
            console.log(value)
            this.stautsAndName(country)
        },
        filterStatus(value, row) {
            var params = {
                "currentPage": this.pageInfo.currentPage,
                "pageSize": this.pageInfo.pageSize,
                'keywords': this.search,
                'status': value
            }
            this.getAnimesData(params)
            return;
        },
        searchName(country) {
            this.pageInfo.currentPage = 1
            // 发送 关键字 请求。分页
            console.log(this.search, this.pageInfo.currentPage, this.pageInfo.pageSize)
            var params = {
                "currentPage": this.pageInfo.currentPage,
                "pageSize": this.pageInfo.pageSize,
                'keywords': this.search,
                'country': country
            }
            // this.status='全部'
            this.getAnimesData(params)
        },
        searchStatus(country) {
            this.pageInfo.currentPage = 1
            var t = 1;
            if (this.status == "全部") {
                t = 2;
            } else if (this.status == "下架") {
                t = 0;
            } else {
                t = 1;
            }
            console.log(this.status, "this.status");
            console.log(t, "状态");
            var params = {
                "currentPage": this.pageInfo.currentPage,
                "pageSize": this.pageInfo.pageSize,
                'status': t,
                'country': country
            }
            // this.search=''
            this.getAnimesData(params)
        },
        stautsAndName(country) {
            var t = 1;
            if (this.status == "全部") {
                t = 2;
            } else if (this.status == "下架") {
                t = 0;
            } else {
                t = 1;
            }
            var params = {
                "currentPage": this.pageInfo.currentPage,
                "pageSize": this.pageInfo.pageSize,
                'status': t,
                'keywords': this.search,
                'country': country
            }
            this.getAnimesData(params)
        },
        addNew() {
            this.title = '新增番剧'
            this.dialogVisible = true
            //原图隐藏，url置为空
            this.isSrcImg = false
            this.srcImg = ''
            //清空表单页面
            this.animeForm = {}

            //发送ajax请求，获取字典数据列表
            this.getD()
        },
        getD() {
            getDictionary().then(res => {
                if (res.data.code === 0) {
                    this.$message({
                        type: 'error',
                        message: res.data.msg
                    })
                    return;
                }
                var data2 = res.data.data
                this.labelD = data2.filter((item) => { return item.type == 1 })
                this.monthD = data2.filter((item) => { return item.type == 2 })
                this.countryD = data2.filter((item) => { return item.type == 3 })
                this.yearD = data2.filter((item) => { return item.type == 4 })
                this.weekD = data2.filter((item) => { return item.type == 5 })
            }).catch(error => {
                // 设置showError: false，可在此处单独设置错误提示
                this.$message({
                    type: 'error',
                    message: '请求接口出错'
                })
            })
        },
        changeLabel() {
            console.log(this.animeForm.labels);
        },
        changeCountry() {

        },
        changeMonth() {

        },
        changeWeek() {

        },
        changeYear() {

        },
        getAnimesData(params) {
            if (params == null) {
                params = {
                    "currentPage": this.pageInfo.currentPage,
                    "pageSize": this.pageInfo.pageSize,
                }
            }
            //发送ajax请求，获取animes数据列表
            getAnimes(params).then(res => {
                console.log(res, "animes数据")
                console.log("发送了后端请求")
                if (res.data.code === 0) {
                    this.$message({
                        type: 'error',
                        message: res.data.msg
                    })
                    return;
                }
                this.animes = res.data.data.records.filter(item => {
                    item.labels = item.labels.split(",")
                    return item
                })
                this.pageInfo.total = Number(res.data.data.total)
            }).catch(error => {
                // 设置showError: false，可在此处单独设置错误提示
                this.$message({
                    type: 'error',
                    message: '请求接口出错'
                })
            })
        }
    }
}
</script>
<style scoped>
.avatar-uploader .el-upload {
    border: 1px dashed #2bc6cc;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #42a123;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
    background-color: rgb(83, 61, 193);
}

.avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>